<?php
/**
 * Created by PhpStorm.
 * User: zhj
 * Date: 2019/1/16
 * Time: 17:03
 */
namespace app\index\controller;
use think\Db;

class Car extends IndexBase{
    public function getCar()
    {
        $uid = session('userid');

        if(!$uid){
            $this->jump(RESULT_REDIRECT, '未登录', url('index/user/login'));
        }

        $list = (new \app\common\model\Car())->search(['userid'=>$uid]);

        $this->assign('list',$list->toArray()['data']);
        return $this->fetch('/index/shopCar');
    }

    /**
     * @param $id 购物车id
     * @param $type 0数量减一，1数量加一
     */
    public function updateNum($product_id,$type=1)
    {
        $car = new \app\common\model\Car();
        $carInfo = $car->where(['id'=>$product_id])->find();
        if($type==1){
            if($carInfo['status']==-1){
                $res = $car->where(['id'=>$product_id])->setField('status',1);
            }
           $res = $car->where(['id'=>$product_id])->setInc('num',1);
        }elseif($type==0){

            if($carInfo['num']){
                $res = $car->where(['id'=>$product_id])->setDec('num',1);
            }else{
                $res = $car->where(['id'=>$product_id])->setField('status',-1);
            }

        }
        if($res){
            $this->ajaxReturn(1,[],'添加成功！');
        }else{
            $this->ajaxReturn(1,[],'添加失败！');
        }
    }

    public function addCar()
    {
        $data = input('param.');
        $validate =  new \app\common\validate\Car();
        $validate->scene('add');
        if(!$validate->check($data)){
            $this->ajaxReturn(0,[],$validate->getError());
        }

        $carRes = (new \app\common\model\Car())->add($data);
        if($carRes){
            $this->ajaxReturn(1,[],'添加成功！');
        }else{
            $this->ajaxReturn(0,[],'添加失败！');
        }
    }

    public function delCar($product_id,$type='delete')
    {
        $res = Db::name('Car')->where(['id'=>$product_id])->setField('status',-1);
        if($res){
            $this->ajaxReturn(1,[],'删除成功！');
        }else{
            $this->ajaxReturn(0,[],'删除失败！');
        }
    }
}